package common

import (
	"bytes"
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
)

func findPowerShell() (string, error) {
	// 尝试常见的位置
	possiblePaths := []string{
		"powershell.exe",
		"pwsh.exe", // PowerShell Core
		filepath.Join(os.Getenv("SystemRoot"), "System32", "WindowsPowerShell", "v1.0", "powershell.exe"),
		filepath.Join(os.Getenv("SystemRoot"), "SysNative", "WindowsPowerShell", "v1.0", "powershell.exe"), // 32位程序在64位系统上
	}

	for _, path := range possiblePaths {
		if _, err := os.Stat(path); err == nil {
			return path, nil
		}
	}

	return "", fmt.Errorf("无法找到 PowerShell 可执行文件")
}

func RunPowerShellCommand(args ...string) (string, string, error) {
	psPath, err := findPowerShell()
	if err != nil {
		return "", "", err
	}

	cmd := exec.Command(psPath, args...)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	err = cmd.Run()
	return stdout.String(), stderr.String(), err
}
